<template>
  <div class="zui-tabs" :class="{ 'align-left': alignTabs === 'left', 'align-center': alignTabs === 'center' }">
    <div
      v-for="(label, idx) in labels"
      :key="idx"
      class="item"
      :class="{ active: activeIndex == idx }"
      @click="activeIndex = idx"
      ref="items"
    >
      {{ label }}
    </div>

    <div v-if="activeItemDom" class="cursor" :style="{ left: cursorOffsetX + 'px', width: cursorWidth + 'px' }"></div>
  </div>
</template>
<script setup>
import { getCurrentInstance, onMounted, ref, watch } from 'vue'

const emit = defineEmits(['update:activeIndex'])

const props = defineProps({
  activeIndex: Number,
  labels: Array,
  alignTabs: {
    type: String,
    default: 'left'
  }
})
const itemDoms = ref()
const activeItemDom = ref()

const activeIndex = ref(props.activeIndex)
const cursorOffsetX = ref(0)
const cursorWidth = ref(0)

watch(
  () => props.activeIndex,
  (value) => {
    activeIndex.value = value
  }
)
watch(activeIndex, (value) => {
  if (itemDoms.value) {
    activeItemDom.value = itemDoms.value[value]
  }

  emit('update:activeIndex', value)
})

watch(activeItemDom, (value) => {
  cursorOffsetX.value = value.offsetLeft + 8
  cursorWidth.value = value.clientWidth - 16
})

onMounted(() => {
  self.value = getCurrentInstance()
  itemDoms.value = getCurrentInstance().refs.items
  const activeItem = itemDoms.value[activeIndex.value]
  activeItemDom.value = activeItem
})
</script>
<style lang="scss" scoped>
.zui-tabs {
  display: flex;
  position: relative;
  box-shadow: var(--box-shadow);
  &.align-center {
    justify-content: center;
  }
  &.align-left {
    .item {
      &:first-child {
        margin-left: 0;
      }
    }
  }

  .item {
    margin: 0 8px;
    padding: 8px 8px 10px 8px;
    cursor: pointer;

    &.active {
      color: var(--zui-color-primary);
      font-weight: bold;
    }
    &:hover {
      color: var(--zui-color-primary);
    }
  }
  .cursor {
    position: absolute;
    bottom: 0;
    left: 100px;
    height: 2px;
    width: 0px;
    background-color: var(--zui-color-primary);
    transition: left 0.2s ease-in-out;
    border-radius: 2px;
  }
}
</style>
